package com.ruoyi.merchant.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.merchant.domain.*;
import com.ruoyi.merchant.dto.ElectrocardiogramDataDto;
import com.ruoyi.merchant.msg.Model.AP02;
import com.ruoyi.merchant.msg.Model.AP49;
import com.ruoyi.merchant.msg.Model.AP50;
import com.ruoyi.merchant.msg.Model.APHP;
import com.ruoyi.merchant.producer.KafkaProducer;
import com.ruoyi.merchant.service.IBluetoothService;
import com.ruoyi.merchant.service.IExceptionValueService;
import com.ruoyi.merchant.util.H002ModelCmdEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class BluetoothServiceImpl implements IBluetoothService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IExceptionValueService exceptionValueService;
    @Autowired
    KafkaProducer kafkaProducer;

    @Override
    public void saveData(Bluetooth bluetooth) {

//        List<String> msg = new ArrayList<>();

        /** 指标类型  指标类型  0  心率异常 ；1  心率报警；2  高压异常；3   低压异常 ；4   高压报警 ； 5 低压报警  ； 6 计步异常 ；7  睡眠异常  ；
         * 8 血氧异常；9 血氧报警； 10 呼吸异常 ； 11 呼吸报警 ； 12  体温异常 ；13  体温报警
         */
//         List<ExceptionValue> exceptionValues = exceptionValueService.selectExceptionValueList(new ExceptionValue());

         /**
         * 步数
         */
        if (bluetooth.getStep() != null){
            C012DataBuShu c012DataBuShu = new C012DataBuShu();
            c012DataBuShu.setId(UUID.fastUUID().toString(true));
            c012DataBuShu.setBuShu(bluetooth.getStep());
            c012DataBuShu.setTerminalTime(new Date());
            c012DataBuShu.setImei(bluetooth.getMac());
            c012DataBuShu.setCustomerId(bluetooth.getCustomerId());
            kafkaProducer.sendMessage(H002ModelCmdEnum.BLUETOOTH00, JSONObject.toJSONString(c012DataBuShu));
        }



        /**
         * 血压、血糖、血氧
         */
        if ( bluetooth.getBloodOxygen() != null
                || bluetooth.getBloodSugar() != null
                || (bluetooth.getBloodDbp() != null && bluetooth.getBloodsbp() != null)){
            APHP aphp = new APHP();
            aphp.setImei(bluetooth.getMac());
            aphp.setBloodOxygen(bluetooth.getBloodOxygen());
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(bluetooth.getBloodSugar())){
                aphp.setBloodSugar(Float.valueOf(bluetooth.getBloodSugar()));
            }
            aphp.setCustomerId(bluetooth.getCustomerId());
            aphp.setHighBloodPressure(bluetooth.getBloodDbp());
            aphp.setLowBloodPressure(bluetooth.getBloodsbp());
            kafkaProducer.sendMessage(H002ModelCmdEnum.IWAPHP, JSONObject.toJSONString(aphp));
        }


        /**
         * 血脂
         */
        if (StringUtils.isNotEmpty(bluetooth.getCholesterol())){
            CholesterolData cholesterolData = new CholesterolData();
            cholesterolData.setId(UUID.fastUUID().toString(true));
            cholesterolData.setCholesterol(Float.valueOf(bluetooth.getCholesterol()));
            cholesterolData.setTerminalTime(new Date());
            cholesterolData.setImei(bluetooth.getMac());
            cholesterolData.setCustomerId(bluetooth.getCustomerId());
            kafkaProducer.sendMessage(H002ModelCmdEnum.BLUETOOTH03, JSONObject.toJSONString(cholesterolData));
        }

        /**
         * 心率
         */
        if (bluetooth.getHeartValue() != null){
            AP49 ap49 = new AP49();
            ap49.setImei(bluetooth.getMac());
            ap49.setHeartRate(bluetooth.getHeartValue());
            ap49.setCustomerId(bluetooth.getCustomerId());
            kafkaProducer.sendMessage(H002ModelCmdEnum.IWAP49, JSONObject.toJSONString(ap49));
        }

        /**
         * 尿酸
         */
        if (StringUtils.isNotEmpty(bluetooth.getUricAcid())){
            UricAcidData uricAcidData = new UricAcidData();
            uricAcidData.setId(UUID.fastUUID().toString(true));
            uricAcidData.setUricAcid(Integer.valueOf(bluetooth.getUricAcid()));
            uricAcidData.setTerminalTime(new Date());
            uricAcidData.setImei(bluetooth.getMac());
            uricAcidData.setCustomerId(bluetooth.getCustomerId());
            kafkaProducer.sendMessage(H002ModelCmdEnum.BLUETOOTH01, JSONObject.toJSONString(uricAcidData));
        }

        /**
         * 心电组数据
         */
        if (CollectionUtils.isNotEmpty(bluetooth.getElectrocardiogramList())){
            ElectrocardiogramData electrocardiogramData = new ElectrocardiogramData();
            electrocardiogramData.setId(UUID.fastUUID().toString(true));
            electrocardiogramData.setHrv(bluetooth.getHrv());
            electrocardiogramData.setBat(bluetooth.getHeartValue());
            electrocardiogramData.setDBP(bluetooth.getBloodDbp());
            electrocardiogramData.setSBP(bluetooth.getBloodsbp());
            electrocardiogramData.setTitle(bluetooth.getTitle());
            electrocardiogramData.setDetail(bluetooth.getDetail());
            electrocardiogramData.setEcg(bluetooth.getEcg());
            electrocardiogramData.setTerminalTime(new Date());
            electrocardiogramData.setImei(bluetooth.getMac());
            electrocardiogramData.setCustomerId(bluetooth.getCustomerId());
            mongoTemplate.save(electrocardiogramData);

            ElectrocardiogramItem electrocardiogramItem = new ElectrocardiogramItem();
            electrocardiogramItem.setElectrocardiogramList(bluetooth.getElectrocardiogramList());
            electrocardiogramItem.setMainId(electrocardiogramData.getId());
            electrocardiogramItem.setTerminalTime(new Date());
            electrocardiogramItem.setId(UUID.randomUUID().toString(true));
            electrocardiogramItem.setCustomerId(bluetooth.getCustomerId());
            mongoTemplate.save(electrocardiogramItem);

//            kafkaProducer.sendMessage(H002ModelCmdEnum.BLUETOOTH02, JSONObject.toJSONString(electrocardiogramData));
        }

        /**
         * 体温
         */
        if (bluetooth.getTemp() != null){
            AP50 ap50 = new AP50();
            ap50.setPower(bluetooth.getPower());
            ap50.setImei(bluetooth.getMac());
            ap50.setTemperature(bluetooth.getTemp());
            ap50.setCustomerId(bluetooth.getCustomerId());
            ap50.setTerminalTime(DateUtils.getTime());
            kafkaProducer.sendMessage(H002ModelCmdEnum.IWAP50, JSONObject.toJSONString(ap50));
        }

        /**
         * 呼吸
         */
        if (StringUtils.isNotEmpty(bluetooth.getRespiratoryRateValue())){
            RespiratoryRateData respiratoryRateData = new RespiratoryRateData();
            respiratoryRateData.setId(UUID.fastUUID().toString(true));
            respiratoryRateData.setRespiratoryRate(Integer.valueOf(bluetooth.getRespiratoryRateValue()));
            respiratoryRateData.setTerminalTime(new Date());
            respiratoryRateData.setImei(bluetooth.getMac());
            respiratoryRateData.setCustomerId(bluetooth.getCustomerId());
            kafkaProducer.sendMessage(H002ModelCmdEnum.BLUETOOTH04, JSONObject.toJSONString(respiratoryRateData));
        }


        /**
         * Hrv
         */
        if (StringUtils.isNotEmpty(bluetooth.getHrv())){
            HrvData hrvData = new HrvData();
            hrvData.setId(UUID.fastUUID().toString(true));
            hrvData.setHrv(Integer.valueOf(bluetooth.getHrv()));
            hrvData.setTerminalTime(new Date());
            hrvData.setImei(bluetooth.getMac());
            hrvData.setCustomerId(bluetooth.getCustomerId());
            kafkaProducer.sendMessage(H002ModelCmdEnum.BLUETOOTH05, JSONObject.toJSONString(hrvData));
        }

        /**
         * ECG测量结果
         */
        if (bluetooth.getEcg() != null){
            EcgData ecgData = new EcgData();
            ecgData.setId(UUID.fastUUID().toString(true));
            ecgData.setEcg(bluetooth.getEcg());
            ecgData.setTerminalTime(new Date());
            ecgData.setImei(bluetooth.getMac());
            ecgData.setCustomerId(bluetooth.getCustomerId());
            kafkaProducer.sendMessage(H002ModelCmdEnum.BLUETOOTH06, JSONObject.toJSONString(ecgData));
        }


        /**
         * 定位数据
         */
        if (StringUtils.isNotEmpty(bluetooth.getLatitude()) && StringUtils.isNotEmpty(bluetooth.getLatitude())){
            AP02 ap02 =  new AP02();
            ap02.setImei(bluetooth.getMac());
            ap02.setAddress(bluetooth.getAddress());
            ap02.setLat(bluetooth.getLatitude());
            ap02.setLon(bluetooth.getLongitude());
            ap02.setCustomerId(bluetooth.getCustomerId());
            ap02.setTerminalTime(DateUtils.getTime());
            kafkaProducer.sendMessage(H002ModelCmdEnum.IWAP02, JSONObject.toJSONString(ap02));
        }
    }

    @Override
    public Page<ElectrocardiogramData> listElectrocardiogram(ElectrocardiogramDataDto electrocardiogramDataDto) {
        Query condition= new Query();

        Page<ElectrocardiogramData> page = new Page<>();


        condition.addCriteria(Criteria.where("imei").is(electrocardiogramDataDto.getImei()));
        condition.addCriteria(Criteria.where("customerId").is(electrocardiogramDataDto.getCustomerId()));

        List<Sort.Order> obj = new ArrayList<>();
        Sort.Order reportTime = new Sort.Order(Sort.Direction.DESC , "terminalTime");
        obj.add(reportTime);
        condition.with(Sort.by(obj));
        int totalCount = (int) mongoTemplate.count(condition, ElectrocardiogramData.class);
        int offset = (int)electrocardiogramDataDto.getPageNum();
        int size = (int) electrocardiogramDataDto.getPageSize();
        page.setPageNum(offset);
        page.setPageSize(size);
        List<ElectrocardiogramData> electrocardiogramDataList = new ArrayList<>();
        if (electrocardiogramDataDto.getPageNum() == 1){
            electrocardiogramDataList = mongoTemplate.find(condition.limit(size), ElectrocardiogramData.class);
        }else {
            electrocardiogramDataList = mongoTemplate.find(condition.skip(((offset - 1 )* size)).limit(size), ElectrocardiogramData.class);
        }
        page.addAll(electrocardiogramDataList);
        page.setTotal(totalCount);

        return page;
    }

    @Override
    public ElectrocardiogramItem selectElectrocardiogramById(String id) {
        Query condition= new Query();
        condition.addCriteria(Criteria.where("mainId").is(id));
        List<ElectrocardiogramItem> electrocardiogramItems = mongoTemplate.find(condition, ElectrocardiogramItem.class);
        if (CollectionUtils.isNotEmpty(electrocardiogramItems)){
            return electrocardiogramItems.get(0);
        }
        return new ElectrocardiogramItem();
    }
}
